<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" width="120%" destroy-on-close @closed="$emit('closed')" align-center fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="70px" label-position="right">
            <el-container>
                <el-header>
                    <el-row>
                        <el-form-item label="收货日期">
                            <!-- <el-date-picker v-model="form.take_deliver_date" type="data" format="YYYY/MM/DD" value-format="YYYY-MM-DD" placeholder="请选择收货日期" /> -->
                            <el-date-picker v-model="form.take_deliver_date" :value-format="'YYYY-MM-DD'" type="data" placeholder="请选择收货日期" />
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                        <div style="margin-left:10px">
                            <el-button v-if="show" type="primary" @click="startSend">开始收货</el-button>
                            <el-button v-else type="primary" @click="stopSend">停止收货</el-button>
                        </div>
                    </el-row>
                </el-header>
                <el-container>
                    <el-aside width="23%">
                        <div style="margin: 15px;height:80%">
                            <div style="text-align: center;margin: 10px;">条码资料</div>
                            <el-form-item label="条码" prop="qrcode">
                                <el-input v-model="info.qrcode" @input="handInput" ref="input" :disabled="weightDis"></el-input>
                                 <!-- @change="handleKeyDown" -->
                            </el-form-item>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="工厂货号" prop="batch_number">
                                        <el-input v-model="info.batch_number" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="批次号" prop="style_number" >
                                        <el-input v-model="info.style_number" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="承制人" prop="apply">
                                        <el-input v-model="info.apply" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="工序" prop="process" >
                                        <el-input v-model="info.process" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="颜色" prop="colour">
                                        <el-input v-model="info.colour" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="类型" prop="color_number" >
                                        <el-input v-model="info.color_number" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="尺码" prop="size">
                                        <el-input v-model="info.size" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="数量" prop="num" >
                                        <el-input v-model="info.num" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="备注" prop="message">
                                        <el-input v-model="info.message" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <el-footer>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="重量" prop="weight">
                                        <el-input v-model="info.weight" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="预计数量" prop="expected_number" >
                                        <el-input v-model="info.expected_number" readonly></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-col :span="12">
                                <el-form-item label="实际数量" prop="weight_num" >
                                    <el-input v-model="info.weight_num" readonly></el-input>
                                </el-form-item>
                            </el-col>
                        </el-footer>
                    </el-aside>
                    <el-main style="height:700px">
                        <sc-form-table ref="table" v-model="form.size_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd show-summary>
                            <el-table-column label="工厂货号" prop="factory_number" align="center"></el-table-column>
                            <el-table-column label="批次号" prop="batch_number" align="center"></el-table-column>
                            <el-table-column label="条码号"  align="center">
                                <template #default="scope">
                                    <div>{{scope.row.barcode}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="工序" prop="process_title" align="center"></el-table-column>
                            <el-table-column label="颜色" prop="colour" align="center"></el-table-column>
                            <el-table-column label="尺码" prop="goods_size" align="center"></el-table-column>
                            <el-table-column label="数量" prop="num" align="center"></el-table-column>
                            <el-table-column label="重量" align="center">
                                <template #default="scope">
                                    <div>{{scope.row.weight}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="超数(+)" prop="overnumber" align="center"></el-table-column>
                            <el-table-column label="超重(+)" prop="overweight" align="center"></el-table-column>
                            <el-table-column label="备注" align="center">
                                <template #default="scope">
                                    <div>{{scope.row.remark}}</div>
                                </template>
                            </el-table-column>
                        </sc-form-table>
                    </el-main>
                </el-container>
            </el-container>
        </el-form>
	</el-dialog>
    <!-- 收货停止 -->
    <el-dialog v-model="dialog.send" title="此次收货停止,是否提交?" width="500" :before-close="handleClose" align-center>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.send = false">取消</el-button>
                <el-button type="primary" @click="submit(1)">确定</el-button>
                <el-button type="primary" @click="submit(2)">确定并打印收货单</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 件数修正 -->
    <el-dialog v-model="dialog.weight" title="件数修正" width="500" :before-close="handleClose" align-center>
        <el-form-item label="请输入正确的件数" prop="edit_number" >
            <el-input v-model="info.edit_number" @keyup.enter="numSub" ref="edit"></el-input>
        </el-form-item>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.weight = false">取消</el-button>
                <el-button type="primary" @click="numSub">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dialog.dbsubmit" :title="dialogMsg" width="500" :before-close="handleClose" align-center>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.dbsubmit = false">取消</el-button>
                <el-button type="primary" @click="secondSubmit(submitType)">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <receipt-print v-if="dialog.print" ref="printDialog" @success="handleSuccess" @closed="dialog.print = false" draggable></receipt-print>
</template>
<script>
import receiptPrint from '../send/receiptPrint.vue';
export default {
  components: { receiptPrint },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '织机扫码收货',
				edit: '编辑仓库',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
            dialog:{
                send:false,
                weight:false,
                print:false,
                dbsubmit:false,
            },
			//表单数据
			form: {
                remark:"",
                take_deliver_date: new Date().toISOString().slice(0, 10),
                delivery_method:2,
                second_conform: 0,
                size_data:[]
			},
            info:{
                qrcode:"",
                batch_number: "",
				style_number: "",
				apply: "",
				process: "",
				colour: "",
				size: "",
				num: "",
				message: "",
                // weight:"0.147",
                weight:"",
                expected_number:"",
                weight_num:"",
                edit_number:'',
                original_barcode:"",
            },
            weight:"",
            addTemplate: {},
            show:true,
            apply:[],
            weightDis:true,
            ports: [],
            port:{},
            connected:null,
            reader:null,
            message:null,
            serialOptions:{
                baudRate: 9600,
                flowControl: 'none',
                dataBits: 8
            },
            infoData:{},
            detailWeight:"",
            dialogMsg: "",
            submitType: "",
		}
	},
    mounted () {
        if ("serial" in navigator) {
            this.chooseSerial()
        } else {
            console.log(false);
        }
    },
    created() {
        this.handInput = this.debounce(this.handInput, 500);
    },
    unmounted() {
        this.cutPort()
        clearTimeout(this.timeoutId);
    },
	methods: {
        // 防抖
        debounce(func, delay) {
            let timeoutId;
            return function(...args) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                func.apply(this, args);
                }, delay);
            };
        },
        // 手动连接
        async chooseSerial(){
            try {
                this.port = await navigator.serial.requestPort();
                this.ports = await navigator.serial.getPorts();
                console.log('this.port :>> ', this.port);
                this.openSear()
            } catch (error) {
                this.$alert(error, "提示", { type: 'error' })
                return;
            }
        },
        // 自动连接
        // async autoConnectSerial() {
        //     try {
        //         const ports = await navigator.serial.getPorts();
        //         if (ports.length > 0) {
        //             // 如果有可用端口，直接选择第一个端口进行连接
        //             this.port = ports[0];
        //             await this.openSear();
        //         } else {
        //             this.$alert("未找到可用串口", "提示", { type: 'error' });
        //         }
        //     } catch (error) {
        //         this.$alert(error, "提示", { type: 'error' });
        //     }
        // },
        async openSear(){
            try {
                await this.port.open(this.serialOptions)
                this.reader = this.port.readable.getReader()
                this.connected = true
                this.readLoop()
            } catch (error) {
                this.$alert(error, "提示", { type: 'error' })
                return;
            }
        },
        async readLoop() {
            try {
                while (this.connected) {
                    const { value, done } = await this.reader.read()
                    if (done) {
                        this.reader.releaseLock()
                        break
                    }
                    this.message = new TextDecoder().decode(value)
                    if(this.message.length==18){
                        let unit = this.message.substr(14,2).toString()
                        let weight = this.message.substr(7,7).trim()
                        if(unit!='kg'){
                            this.info.weight = weight / 1000
                        }else{
                            this.info.weight = weight
                        }
                    }
                }
            } catch (error) {
                this.$alert(error, "提示", { type: 'error' })
            }
        },
        // 断开串口
        async cutPort(){
            if (this.port && this.connected) {
	            await this.reader.cancel();
	            await this.port.close();
	            this.port = "";
            } else {
                // this.$alert("错误", "提示", { type: 'error' })
				console.log('11')
            }
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
                    this.dialog.send = false
					var res = [];
                    res = await this.$API.produce.contract.loomScanTakeDelivery.post(this.form);
                    if (res.code == 1) {
                        this.cutPort()
                        this.visible = false;
                        if(e==1){
                            this.$emit('success', this.form, this.mode)
                            this.visible = false;
                            this.$message.success("操作成功")
                        }else{
                            console.log('e :>> ', e);
                            var reqData = { deliver_no: res.data.deliver_no, contract_no:res.data.contract_no};
                            var print = await this.$API.print.sendPrint.get(reqData);
                            if (print.code == 1) {
                                this.$emit('success', this.form, this.mode,print.data)
                            } else {
                                this.$alert(print.message, "提示", { type: "error" });
                                this.isSaveing = false;
                            }
                        }
                    }else if (res.code == 3) {
                        this.dialogMsg = res.message
                        this.submitType = e
                        this.dialog.dbsubmit = true
                    } else {
                        this.$alert(res.message, "提示", { type: 'error' })
                        this.isSaveing = false;
                    }
				} else {
					return false;
				}
			})
		},
        secondSubmit(e){
            this.form.second_conform = 1
            this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
                    this.dialog.dbsubmit = false
					var res = [];
                    res = await this.$API.produce.contract.loomScanTakeDelivery.post(this.form);
                    if (res.code == 1) {
                        this.cutPort()
                        this.visible = false;
                        if(e==1){
                            this.$emit('success', this.form, this.mode)
                            this.visible = false;
                            this.$message.success("操作成功")
                        }else{
                            var reqData = { deliver_no: res.data.deliver_no, contract_no:res.data.contract_no};
                            var print = await this.$API.print.sendPrint.get(reqData);
                            if (print.code == 1) {
                                this.$emit('success', this.form, this.mode,print.data)
                            } else {
                                this.$alert(print.message, "提示", { type: "error" });
                                this.isSaveing = false;
                            }
                        }
                    }
				} else {
					return false;
				}
			})
        },
		/**开始收货*/
        startSend(){
            this.show = false
            this.weightDis = false
            this.$nextTick(()=>{
                this.$refs.input.focus()
            })
        },
		/**停止收货*/
        stopSend(){
            this.dialog.send = true
            this.cutPort()
        },
        handInput(e){
            this.handleKeyDown(e)
        },
        /**扫码枪事件*/
        async handleKeyDown(e) {
            this.info.qrcode = ''
            var res = await this.$API.produce.contract.loomScanOrderDetail.get({qrcode: e});
            if(res.code==1){
                this.detailWeight = res.data.detail.weight
                this.infoData = res.data
                this.info.batch_number = res.data.contract.batch_number
                this.info.style_number = res.data.contract.goods.style_name
                this.info.apply = res.data.contract.referred_as
                this.info.process = res.data.contract.two_process_title
                this.info.colour = res.data.contract.goods.colour
                this.info.color_number = res.data.contract.goods.color_type == 1 ? "主色" : "加色"
                this.info.size = res.data.detail.goods_size
                this.info.num = Number(res.data.detail.curr_num)
                this.info.weight_num = res.data.detail.curr_num
                this.info.message = res.data.contract.remark
                this.info.barcode = res.data.detail.barcode
                this.info.original_barcode = res.data.detail.barcode
                this.info.expected_number = (Number(this.info.weight*1000) / Number(res.data.detail.weight)).toFixed(0)
				this.info.edit_number =  res.data.detail.curr_num
                if(this.info.expected_number > (this.info.num+1) || this.info.expected_number < (this.info.num-1)){
                    if(this.info.expected_number > (this.info.num+1)){
                        this.dialog.weight = true
                        setTimeout(()=>{
                            this.$refs.edit.focus()
                        },500)
                    }
                    if(this.info.expected_number < (this.info.num-1) ){
                        this.dialog.weight = true
                        setTimeout(()=>{
                            this.$refs.edit.focus()
                        },500)
                    }
                    var MusicDuang = new Audio('https://zhiqiu.mzth.cn/static/img/duang.mp3');
                    MusicDuang.play()
                }else{
                    let overweight = ((this.info.weight - (this.info.edit_number * this.infoData.detail.weight/1000))).toFixed(3);
                    let math = Number(overweight*1000) / Number(this.detailWeight)
                    var MusicYes = new Audio('https://zhiqiu.mzth.cn/static/img/yes.mp3');
                    MusicYes.play()
                    let tabData = []
                    tabData.push({
                        contract_no : res.data.contract.contract_no,
                        batch_number : res.data.contract.batch_number,
                        factory_number : res.data.contract.factory_number,
                        process : res.data.contract.two_process_title,
                        colour : res.data.contract.goods.colour,
                        goods_size : res.data.detail.goods_size,
                        num : this.info.weight_num,
                        remark : res.data.contract.remark,
                        weight : this.info.weight,
                        total_weight : this.info.weight,
                        goods_id : res.data.detail.goods_id,
                        process_title : res.data.contract.two_process_title,
                        // overnumber : this.info.expected_number - res.data.detail.curr_num,
                        // overweight : (this.info.weight - Number(res.data.detail.curr_num * res.data.detail.weight/1000)).toFixed(2),
                        overweight: overweight,
                        overnumber : math < 0? Math.ceil(math):Math.floor(math),
                        barcode:this.info.barcode,
                        original_barcode:this.info.barcode
                    })
                    // this.form.size_data = tabData
                    let existingIds = this.form.size_data.map(item => item.barcode);
                    for(let i = tabData.length - 1; i >= 0; i--){
                        if(existingIds.includes(tabData[i].barcode)){
                            this.$alert('请勿重复扫码!', "提示", { type: 'error' })
                            tabData.splice(i, 1);
                        }
                    }
                    this.form.size_data = [...this.form.size_data,...tabData]
                }
            }else{
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
		/**修正确定按钮点击*/
        numSub(){
            var MusicYes = new Audio('https://zhiqiu.mzth.cn/static/img/yes.mp3');
            MusicYes.play()
            this.dialog.weight = false
            let tabData = [];
            let overweight = ((this.info.weight - (this.info.edit_number * this.infoData.detail.weight/1000))).toFixed(3);
            let math = Number(overweight*1000) / Number(this.detailWeight)
            tabData.push({
                contract_no : this.infoData.contract.contract_no,
                batch_number : this.infoData.contract.batch_number,
                factory_number : this.infoData.contract.factory_number,
                process : this.infoData.contract.two_process_title,
                colour : this.infoData.contract.goods.colour,
                goods_size : this.infoData.detail.goods_size,
                num : this.info.edit_number,
                remark : this.infoData.contract.remark,
                weight : this.info.weight,
                total_weight : this.info.weight,
                goods_id : this.infoData.detail.goods_id,
                process_title : this.infoData.contract.two_process_title,
                // overnumber : this.info.expected_number - this.info.edit_number,
                // overweight : Number(Number(this.info.expected_number - this.info.edit_number) * this.infoData.detail.weight/1000).toFixed(2),
                overweight: overweight,
                overnumber : math < 0? Math.ceil(math):Math.floor(math),
                barcode:this.info.barcode,
                original_barcode:this.info.barcode
            })
            let existingIds = this.form.size_data.map(item => item.original_barcode);
            for(let i = tabData.length - 1; i >= 0; i--){
                if(existingIds.includes(tabData[i].original_barcode)){
                    this.$alert('请勿重复扫码!', "提示", { type: 'error' })
                    tabData.splice(i, 1);
                }
            }
            this.form.size_data = [...this.form.size_data,...tabData]
        },
	}
}
</script>

<style></style>
